﻿
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCSoict.Models;

using System.Data.SqlClient;
using Newtonsoft.Json;
using System;

namespace MVCSoict.Controllers
{
    public class ActionController : Controller
    {
        private staffsoictEntities1 db = new staffsoictEntities1();
        private JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        };
        // GET: /Action/
        public ActionResult Index()
        {
            return View(db.Actions.ToList());
        }

        public string Select(string keyword, int page, int pagesize)
        {
            string jsonResult = string.Empty;
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "action_select"))
                {
                    using (var context = new staffsoictEntities1())
                    {
                        var actions = from a in context.Actions
                                      where a.name.Contains(keyword) || a.description.Contains(keyword)
                                      orderby a.id
                                      select a;

                        var pageData = actions.Skip((page - 1) * pagesize).Take(pagesize).ToList();
                        foreach (var action in pageData)
                        {
                            jsonResult += JsonConvert.SerializeObject(action, jsonSettings);
                        }
                    }
                }
            }
            return jsonResult;
        }
        //tested
        public string Add(string name, string description) 
        {
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "action_add"))
                {
                    MVCSoict.Models.Action action = new Models.Action();
                    action.name = name;
                    action.id = GetNextId();
                    action.description = description;
                    string res = string.Empty;
                    try
                    {
                        db.Actions.Add(action);
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(action, jsonSettings);
                    }
                    catch (System.Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string GetNextId()
        {
            var actions = from a in db.Actions
                        orderby a.id
                        select a;
            int count = actions.Count();
            string id = string.Empty;
            string nextid = string.Empty;
            int delta = 0;
            if (count > 0)
            {
                id = actions.ToList()[count - 1].id;
                int y = Convert.ToInt32(id[4].ToString());
                if (y < 9)
                {
                    delta = 1;
                }
                if (y >= 9 && y < 99)
                {
                    delta = 2;
                }
                if (y >= 99 && y < 999)
                {
                    delta = 3;
                }
                for (int i = 0; i < (id.Count() - delta); i++)
                {
                    nextid += id[i].ToString();
                }
                nextid += (y + 1).ToString();
            }
            else
            {
                nextid = "A0000";
            }
            return nextid;
        }

        //tested
        public string Update(string id, string name, string description)
        {
            if (Session["username"] != null)
            {
                if (MVCSoict.Models.Authentication.Author.Authorize(Session["username"].ToString(), "action_update"))
                {
                    MVCSoict.Models.Action action = new Models.Action();
                    action.name = name;
                    action.id = id;
                    action.description = description;
                    string res = string.Empty;
                    try
                    {
                        db.Entry(action).State = EntityState.Modified;
                        db.SaveChanges();
                        res = JsonConvert.SerializeObject(action, jsonSettings);
                    }
                    catch (Exception ex)
                    {
                        res = ex.Message;
                    }
                }
            }
            return res;
        }

        public string Get(string id)
        {
            string res = string.Empty;
            try
            {
                var actions = from a in db.Actions
                            where a.id.Equals(id)
                            select a;
                if ((actions.ToList<MVCSoict.Models.Action>().Count() > 0))
                    res = JsonConvert.SerializeObject(actions.ToList<MVCSoict.Models.Action>()[0],jsonSettings);
            }
            catch (Exception ex)
            {
                res = ex.Message;
            }
            return res;
        }

        // GET: /Action/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MVCSoict.Models.Action action = db.Actions.Find(id);
            if (action == null)
            {
                return HttpNotFound();
            }
            return View(action);
        }

        // GET: /Action/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Action/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id,name,description")] MVCSoict.Models.Action action)
        {
            if (ModelState.IsValid)
            {
                db.Actions.Add(action);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(action);
        }

        // GET: /Action/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MVCSoict.Models.Action action = db.Actions.Find(id);
            if (action == null)
            {
                return HttpNotFound();
            }
            return View(action);
        }

        // POST: /Action/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "id,name,description")] MVCSoict.Models.Action action)
        {
            if (ModelState.IsValid)
            {
                db.Entry(action).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(action);
        }

        // GET: /Action/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MVCSoict.Models.Action action = db.Actions.Find(id);
            if (action == null)
            {
                return HttpNotFound();
            }
            return View(action);
        }

        // POST: /Action/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            MVCSoict.Models.Action action = db.Actions.Find(id);
            db.Actions.Remove(action);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
